﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using vJoyInterfaceWrap;
using System.Threading;

namespace OAO
{
    class JoyControl
    {
        private uint id = 3;
        public enum JOY_KEYS
        {
            Item1 = 0x1<<0,
            Item2 = 0x1 << 1,
            Item3 = 0x1 << 2,
            Item4 = 0x1 << 3,
            Item5 = 0x1 << 4,
            Item6 = 0x1 << 5,
            Item7 = 0x1 << 6,
            SkillQ = 0x1 << 7,
            SkillW = 0x1 << 8,
            SkillE = 0x1 << 9,
            SkillR = 0x1 << 10,
            SkillD = 0x1 << 11,
            SkillF = 0x1 << 12
        };

        public vJoy joystick;
        private vJoy.JoystickState iReport;
        public string sta;

        public JoyControl()
        {
            this.joystick = new vJoy();
            this.iReport = new vJoy.JoystickState();
            if (!this.joystick.vJoyEnabled())
            {
                this.sta = "vJoy driver not enabled: Failed Getting vJoy attributes.";
            }
            else
            {
                this.sta = "Vendor: " + this.joystick.GetvJoyManufacturerString() + "\nProduct :" + this.joystick.GetvJoyProductString() + "\nVersion Number:" + this.joystick.GetvJoySerialNumberString();
                this.iReport.AxisXRot = 16500;
                this.iReport.AxisYRot = 16500;
                this.iReport.AxisZRot = 16500;
                this.iReport.AxisX = 16500;
                this.iReport.AxisY = 16500;
                this.iReport.AxisZ = 16500;
                if (this.joystick.UpdateVJD(this.id, ref this.iReport))
                    return;
                this.joystick.AcquireVJD(this.id);
            }
        }

        public void Key(JOY_KEYS k)
        {
            this.iReport.bDevice = (byte)0;
            this.iReport.Buttons |= (uint)k;
            if (!this.joystick.UpdateVJD(this.id, ref this.iReport))
            {
                this.joystick.AcquireVJD(this.id);
            }
            Thread.Sleep(33);
            this.iReport.Buttons &= (uint)~k;

            if (this.joystick.UpdateVJD(this.id, ref this.iReport))
            {
                this.joystick.AcquireVJD(this.id);
            }
        }

        public void KeyUp(JOY_KEYS k)
        {
            this.iReport.bDevice = (byte)0;
            this.iReport.Buttons &= (uint)~k;

            if (this.joystick.UpdateVJD(this.id, ref this.iReport))
            {
                this.joystick.AcquireVJD(this.id);
            }
        }

        public void KeyDown(JOY_KEYS k)
        {
            this.iReport.bDevice = (byte)0;            
            this.iReport.Buttons |= (uint)(k);

            if (this.joystick.UpdateVJD(this.id, ref this.iReport))
            {
                this.joystick.AcquireVJD(this.id);
            }
        }
    }
}
